package com.hu.common.util.adm;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

/**
 * @ClassName XMLHelper
 * @Description xml操作工具类
 * @author 355760
 **/
public class XMLHelper {

    /**
     * 对象转xml字符串
     *
     * @param obj       java对象
     * @param xmlHeader xml头部
     * @return xml字符串
     */
    public static String object2xmlStr(Object obj, String xmlHeader) throws Exception {
        // 创建输出流
        StringWriter sw = new StringWriter();
        if (Assert.notEmpty(xmlHeader)) {
            sw.write(xmlHeader);
            sw.write(System.lineSeparator());
        }

        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        // 格式化xml输出的格式
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        // 格式化xml输出格式，并去除 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        // 将对象转换成输出流形式的xml
        marshaller.marshal(obj, sw);

        return sw.toString();
    }

    public static String addSpace(String xml) {
        return xml.replaceAll("/>", " />");
    }

    public static String appendXmlHeader(String xml, String xmlHeader) {
        return xmlHeader.concat(System.lineSeparator()).concat(xml);
    }

    public static String trimStr(String xml) {
        StringBuilder sb = new StringBuilder();
        for (String s : xml.split("\n")) {
            sb.append(s.trim());
        }
        return sb.toString();
    }
}
